const express = require('express') //引入express
const app = express() //使用express
const config = require('./config/config.json')
// const proxy = require('http-proxy-middleware') # version < 1.*.*
const { createProxyMiddleware } = require('http-proxy-middleware');


var allowCores = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*'); //设置允许的来源
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');// 允许的请求方法
    res.header('Access-Control-Allow-Headers', 'Content-Type,target,ccc,DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X_Requested_With,If-Modified-Since,Cache-Control, Accept-Language, Origin, Accept-Encoding'); //允许的头部
    // res.header('Access-Control-Expose-Headers', 'target,ccc'); //额外允许的头部 XMLHttpRequest对象的getResponseHeader()方法获取值
    res.header('Access-Control-Allow-Credentials','true'); //
    if (req.method == 'OPTIONS') { //如果是options方法，直接返回200.解决跨域响应问题
        res.sendStatus(204)
    } else {
        next()
    } 
}
app.use(allowCores); //使用跨域中间件

app.use('/', createProxyMiddleware({
    target: 'http://localhost:8080', //目标服务器
    changeOrigin: true, // 默认false，是否需要改变原始主机头为目标URL
    ws: true, // 是否代理websockets
    onProxyReq: function (proxyReq, req, res) {
        console.log("aaaa")
    },
    onProxyRes: function (proxyRes, req, res) {
        console.log("bbb")
      const _write = res.write;
      const _end = res.end;
      var body = new Buffer.from('')
      try{
          Object.assign(res, {
          write: (chunk) => {
              body = Buffer.concat([body, chunk]);
          },
          end: () => {
              var result = body
              console.log(body)
              var buf = Buffer.from(result, 'utf-8');
              console.log(buf.toString())
              _write.call(res, buf)
              _end.call(res)
          }
          })
      } catch(err) {
          console.log(err)
      }
    }
}))


app.listen(config.port)
console.log('app started at port ' + config.port)